import axios from 'axios'
import qs from 'qs'
import store from '../vuex/store'

// axios 配置
// axios.defaults.timeout = 5000; //延迟模拟
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
axios.defaults.baseURL = 'http://localhost:8080/api';

//POST传参序列化，以及全局token
axios.interceptors.request.use((config) => {

    // config.headers['Access-Control-Allow-Origin'] = '*';
    // config.headers['Access-Control-Allow-Methods']='POST';
    // config.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type';

    if (store.state.token) {  
        // 判断是否存在token，如果存在的话，则每个http header都加上token
        config.headers.Authorization = `${store.state.token}`;
    }

    if(config.method  === 'post'){
        config.data = qs.stringify(config.data);
    }

    return config;
},(error) =>{
    return Promise.reject(error);
});

//返回状态判断
axios.interceptors.response.use((res) =>{
        // 后台返回“失败”的信息
        if(!res.data.success){
            // _.toast(res.data.msg); 此处应该有弹窗
            // return Promise.reject(res);
        }
    return res;
}, (error) => {
    // 弹窗
    return Promise.reject(error);
});

export function post(url, params) {
    return new Promise((resolve, reject) => {
        axios.post(url, params)
            .then(response => {
                resolve(response.data);
            }, err => {
                reject(err);
            })
            .catch((error) => {
               reject(error)
            })
    })
}

export function get(url, params) {
    return new Promise((resolve, reject) => {
        axios.get(url, params)
            .then(response => {
                resolve(response.data);
            }, err => {
                reject(err);
            })
            .catch((error) => {
               reject(error)
            })
    })
}

export default {
    get,
    post
}
